package com.baijiaxing.weixin.family.message.units;

import com.baijiaxing.weixin.family.message.enums.FamilyMessageTypeEnum;
import com.baijiaxing.weixin.family.message.model.FamilyTextMessage;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.Date;

/**
 * Created by June on 2016/12/18.
 */
public class CreateFamilyTextMessage {
    /**
     * <p>Title: replyText</p>
     * <p>Description: 生产文本消息回复内容</p>
     * @param content
     * @param toUser
     * @return
     */
    public static String replyText(String content, String toUser, String fromUserName){
        Document doc = DocumentHelper.createDocument();
        Element root = doc.addElement("xml");
        root.addElement("ToUserName").addText(toUser);
        //获取官方微信公众号
        root.addElement("FromUserName").addText(fromUserName);
        root.addElement("CreateTime").addText(String.valueOf(new Date().getTime()));
        root.addElement("MsgType").addText(FamilyMessageTypeEnum.TEXT.getKey());
        root.addElement("Content").addText(content);
        return doc.asXML();
    }


    /**
     * <p>Title: parseText</p>
     * <p>Description: 解析文本消息</p>
     * @param msgXml
     * @return
     * @throws DocumentException
     */
    public static FamilyTextMessage parseText(String msgXml) throws DocumentException {
        FamilyTextMessage textMsg = new FamilyTextMessage();
        Document doc = DocumentHelper.parseText(msgXml);
        Element root = doc.getRootElement();
        textMsg.setToUserName(root.element("ToUserName").getStringValue());
        textMsg.setFromUserName(root.element("FromUserName").getStringValue());
        textMsg.setCreateTime(Long.parseLong(root.element("CreateTime").getStringValue()));
        textMsg.setMsgType(root.element("MsgType").getStringValue());
        textMsg.setContent(root.element("Content").getStringValue());
        textMsg.setMsgId(Long.parseLong(root.element("MsgId").getStringValue()));
        textMsg.setAgentID(Integer.valueOf(root.element("AgentID").getStringValue()));
        return textMsg;
    }
}
